from multiprocessing import Process
from multiprocessing.shared_memory import SharedMemory
import struct


def modify_shared_float(shm_name):
    # 连接到共享内存
    shm = SharedMemory(name=shm_name)

    # 读取当前值（解包为浮点数）
    current_value, = struct.unpack('d', shm.buf[:8])

    # 修改值并写回内存
    new_value = current_value * 2
    shm.buf[:8] = struct.pack('d', new_value)

    # 关闭共享内存连接
    shm.close()


if __name__ == "__main__":
    # 创建共享内存，存储一个双精度浮点数（8字节）
    shm = SharedMemory(create=True, size=8)

    # 写入初始值 3.14
    shm.buf[:8] = struct.pack('d', 3.14)

    # 创建子进程修改共享值
    p = Process(target=modify_shared_float, args=(shm.name,))
    p.start()
    p.join()

    # 读取修改后的值
    modified_value, = struct.unpack('d', shm.buf[:8])
    print(f"Modified value: {modified_value}")  # 输出: 6.28

    # 清理共享内存
    shm.close()
    shm.unlink()